//
//  ChannelViewController.m
//  ShrimpCrowdordering
//
//  Created by 郑洲 on 2018/7/25.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "ChannelViewController.h"

#import "SignInViewController.h"
#import "ChoosePKViewController.h"
#import "GameDetailViewController.h"
#import "ChanelDetailViewController.h"
#import "MoreDetailViewController.h"

#import "MineViewController.h"
#import "MessageViewController.h"
#import "ConcernViewController.h"

#import "ChannelTableViewCell.h"
#import "KDCycleBannerView.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>

@interface ChannelViewController ()<UITableViewDelegate, UITableViewDataSource, KDCycleBannerViewDataSource, KDCycleBannerViewDelegate>{
    UIButton *messageBtn;
}

@property (nonatomic, strong) BaseTableView *tableView;
@property (nonatomic, strong) KDCycleBannerView * cycleBannerViewBottom;//轮播图

@property (nonatomic, strong) NSArray *circleArray;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger totalPage;

@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerViewController  *playerView;

@end

@implementation ChannelViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [UIApplication sharedApplication].statusBarStyle=UIStatusBarStyleDefault;
    [self getNoteNum];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.circleArray = [NSArray array];
    self.dataArray = [NSMutableArray array];
    self.currentPage = 1;
    
    [self setNavBar];
    [self setTableView];
    
    [self getCircleData];
    
    [kNotificationCenter addObserver:self selector:@selector(headerRefresh) name:@"ReloadChannel" object:nil];
}

- (void)getCircleData {
    [HttpManager postHttpRequestByGet:[NSString stringWithFormat:@"%@api/sowing",REQUESTHEADER] andParameter:nil success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
        if ([status isEqualToString:@"200"]) {
            self.circleArray = successResponse[@"data"][@"list"];
            [self.cycleBannerViewBottom reloadDataWithCompleteBlock:nil];
        }else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"message"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

- (void)getData {
    if (!kNSUDefaultReadKey(@"userId")) {
        return;
    }
    NSDictionary *parameter = @{@"page":[NSNumber numberWithInteger:_currentPage],@"userId":kNSUDefaultReadKey(@"userId")};
    [HttpManager postHttpRequestByGet:[NSString stringWithFormat:@"%@api/channelList",REQUESTHEADER] andParameter:parameter success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
        if ([status isEqualToString:@"200"]) {
            if (self.currentPage == 1) {
                [self.dataArray removeAllObjects];
            }
            self.totalPage = [successResponse[@"data"][@"pages"] integerValue];
            NSError *error = nil;
            for (NSDictionary *dic in successResponse[@"data"][@"list"]) {
                ChannelModel *model = [[ChannelModel alloc] initWithDictionary:dic error:&error];
                [self.dataArray addObject:model];
            }
            if (self.totalPage == self.currentPage) {
                self.tableView.mj_footer.hidden = YES;
            }
            if ([successResponse[@"data"][@"list"] count] == 0) {
                [HttpManager showNoteMsg:@"暂无频道数据"];
                self.tableView.mj_footer.hidden = YES;
            }
            [self.tableView reloadData];
        }else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"message"]]];
        }
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }else if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

- (void)turnToConcern {
    ConcernViewController *vc = [[ConcernViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)setNavBar {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(44) + STATUS_BAR_HEIGHT)];
    [self.view addSubview:view];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, STATUS_BAR_HEIGHT + ScreenX375(14), SCREEN_WIDTH, ScreenX375(17))];
    titleLabel.text = @"频道";
    titleLabel.font = Kfont(17);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = FONTCOLOR_BLACK;
    [view addSubview:titleLabel];
    
    UIImageView *headImage = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(16), ScreenX375(4) + STATUS_BAR_HEIGHT, ScreenX375(37), ScreenX375(37))];
    [headImage sd_setImageWithURL:[NSURL URLWithString:kNSUDefaultReadKey(@"pic")] placeholderImage:nil options:SDWebImageRetryFailed];
    headImage.layer.cornerRadius = ScreenX375(18.5);
    headImage.clipsToBounds = YES;
    headImage.userInteractionEnabled = YES;
    [view addSubview:headImage];
    
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] init];
    [tapGR addTarget:self action:@selector(turnToMine)];
    [headImage addGestureRecognizer:tapGR];
    
    messageBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - ScreenX375(32), ScreenX375(12) + STATUS_BAR_HEIGHT, ScreenX375(20), ScreenX375(22))];
    [messageBtn setImage:ImageWithName(@"消息") forState:UIControlStateNormal];
    [messageBtn addTarget:self action:@selector(turnToMessage) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:messageBtn];
}

- (void)getNoteNum {
    if (!kNSUDefaultReadKey(@"userId")) {
        return;
    }
    [HttpManager postHttpRequestByGet:[NSString stringWithFormat:@"%@api/getMassageType",REQUESTHEADER] andParameter:@{@"userId":kNSUDefaultReadKey(@"userId")} success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
        if ([status isEqualToString:@"200"]) {
            if ([successResponse[@"data"][@"list"] count] == 0) {
                [self->messageBtn setImage:ImageWithName(@"消息2") forState:UIControlStateNormal];
            }else {
                [self->messageBtn setImage:ImageWithName(@"消息") forState:UIControlStateNormal];
            }
            [self.tableView reloadData];
        }else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

- (void)turnToMine {
    MineViewController *vc = [[MineViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)turnToMessage {
    MessageViewController *vc = [[MessageViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)pkClick {
    ChoosePKViewController *vc = [[ChoosePKViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)signIn {
    SignInViewController *vc = [[SignInViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)setTableView {
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, ScreenX375(44) + STATUS_BAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - TAB_BAR_HEIGHT - ScreenX375(44) - STATUS_BAR_HEIGHT)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.rowHeight = ScreenX375(430);
    [self.view addSubview:self.tableView];
    
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < 12; i++) {
        NSString *imageName = [NSString stringWithFormat:@"%d",i];
        [arr addObject:ImageWithName(imageName)];
    }
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    [header setImages:arr forState:MJRefreshStateRefreshing];
    self.tableView.mj_header = header;
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    [self.tableView.mj_header beginRefreshing];
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(285))];
    self.tableView.tableHeaderView = headView;
    
    UIView *shadowV = [[UIView alloc] initWithFrame:CGRectMake(ScreenX375(19), ScreenX375(20), SCREEN_WIDTH - ScreenX375(38), ScreenX375(164))];
    shadowV.layer.cornerRadius = ScreenX375(8);
    shadowV.layer.shadowColor = RGBACOLOR(0, 0, 0, 0.1).CGColor;
    shadowV.layer.shadowOffset = CGSizeMake(0, 4);
    shadowV.layer.shadowOpacity = 1;
    shadowV.layer.shadowRadius = 12;
    shadowV.backgroundColor = [UIColor whiteColor];
    [headView addSubview:shadowV];
    
    self.cycleBannerViewBottom = [KDCycleBannerView new];
    self.cycleBannerViewBottom.frame = CGRectMake(ScreenX375(19), ScreenX375(20), SCREEN_WIDTH - ScreenX375(38), ScreenX375(164)); //位置及宽高
    self.cycleBannerViewBottom.datasource = self;
    self.cycleBannerViewBottom.delegate = self;
    self.cycleBannerViewBottom.continuous = YES; //是否连续显示
    self.cycleBannerViewBottom.autoPlayTimeInterval = 4; //时间间隔
    self.cycleBannerViewBottom.layer.cornerRadius = ScreenX375(8);
    self.cycleBannerViewBottom.clipsToBounds = YES;
    [headView addSubview:self.cycleBannerViewBottom];
    
    NSArray *imageArr = @[@"签到",@"PK",@"关注"];
    for (int i = 0; i < 3; i++) {
        UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(50) + i * ScreenX375(116), ScreenX375(208), ScreenX375(42), ScreenX375(42))];
        imageV.image = ImageWithName(imageArr[i]);
        [headView addSubview:imageV];
        
        UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(50) + i * ScreenX375(116), ScreenX375(260), ScreenX375(42), ScreenX375(13))];
        noteLabel.text = imageArr[i];
        noteLabel.textColor = REXADECIMALCOLOR(@"#666666");
        noteLabel.font = Kfont(13);
        noteLabel.textAlignment = NSTextAlignmentCenter;
        [headView addSubview:noteLabel];
        
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(50) + i * ScreenX375(116), ScreenX375(208), ScreenX375(42), ScreenX375(65))];
        if (i == 0) {
            [button addTarget:self action:@selector(signIn) forControlEvents:UIControlEventTouchUpInside];
        }else if (i == 1) {
            [button addTarget:self action:@selector(pkClick) forControlEvents:UIControlEventTouchUpInside];
        }else {
            [button addTarget:self action:@selector(turnToConcern) forControlEvents:UIControlEventTouchUpInside];
        }
        [headView addSubview:button];
    }
}

- (void)headerRefresh {
    _currentPage = 1;
    [self getData];
    self.tableView.mj_footer.hidden = NO;
}

- (void)footerRefresh {
    if (_currentPage <= _totalPage) {
        
        _currentPage++;
        [self getData];
        // 结束刷新
        [self.tableView.mj_footer endRefreshing];
    }else{
        
//        [HttpManager showNoteMsg:@"已经到底啦"];
        // 结束刷新
        [self.tableView.mj_footer endRefreshing];
        self.tableView.mj_footer.hidden = YES;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ChannelTableViewCell *cell = [ChannelTableViewCell cellWithTableView:tableView andIndexPath:indexPath];
    cell.channelModel = _dataArray[indexPath.row];
    ChannelModel *model = _dataArray[indexPath.row];
    cell.concernClick = ^{
        [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@api/concernChannel",REQUESTHEADER] andParameter:@{@"userId":kNSUDefaultReadKey(@"userId"),@"channelId":model.Id} success:^(id successResponse) {
            NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
            if ([status isEqualToString:@"200"]) {
                if ([model.isFollow integerValue]) {
                    model.isFollow = @"0";
                    model.fensNum = [NSString stringWithFormat:@"%ld",[model.fensNum integerValue] - 1];
                    [HttpManager showNoteMsg:@"取消关注成功"];
                }else {
                    model.isFollow = @"1";
                    [HttpManager showNoteMsg:@"关注成功"];
                    model.fensNum = [NSString stringWithFormat:@"%ld",[model.fensNum integerValue] + 1];
                }
                [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            }else {
                [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
            }
        } andFailure:^(id failureResponse) {
            [HttpManager showFail];
        }];
    };
    cell.playClick = ^{
        [self playVideoWithUrl:model.pic];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ChannelModel *model = _dataArray[indexPath.row];
    ChanelDetailViewController *vc = [[ChanelDetailViewController alloc] init];
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)playVideoWithUrl:(NSString *)url {
    NSString *playString = url;
    //视频播放的url
    NSURL *playerURL = [NSURL URLWithString:playString];
    //初始化
    self.playerView = [[AVPlayerViewController alloc]init];
    //AVPlayerItem 视频的一些信息  创建AVPlayer使用的
    AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:playerURL];
    //通过AVPlayerItem创建AVPlayer
    self.player = [[AVPlayer alloc]initWithPlayerItem:item];
    //给AVPlayer一个播放的layer层
    AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    layer.frame = CGRectMake(0, 100, self.view.frame.size.width, 200);
    layer.backgroundColor = [UIColor greenColor].CGColor;
    //设置AVPlayer的填充模式
    layer.videoGravity = AVLayerVideoGravityResize;
    //设置AVPlayerViewController内部的AVPlayer为刚创建的AVPlayer
    self.playerView.player = self.player;
    //关闭AVPlayerViewController内部的约束
    self.playerView.view.translatesAutoresizingMaskIntoConstraints = YES;
    [self presentViewController:self.playerView animated:YES completion:nil];
}

#pragma mark 轮播图代理委托

- (NSArray *)numberOfKDCycleBannerView:(KDCycleBannerView *)bannerView{
    NSMutableArray *urlArray = [NSMutableArray array];
    for (int i = 0; i < _circleArray.count; i++) {
        NSString *url = [NSString stringWithFormat:@"%@",_circleArray[i][@"pic"]];
        [urlArray addObject:url];
    }
    return urlArray;
}

- (UIViewContentMode)contentModeForImageIndex:(NSUInteger)index{
    return UIViewContentModeScaleAspectFill;
}

- (void)cycleBannerView:(KDCycleBannerView *)bannerView didSelectedAtIndex:(NSUInteger)index{
    NSLog(@"点击了第%ld个",(long)index);
    if (_circleArray[index][@"link"]) {
        if ([_circleArray[index][@"link"] length] > 0) {
            GameDetailViewController *vc = [[GameDetailViewController alloc] init];
            vc.proDic = _circleArray[index];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
